

#import "LoginController.h"
#import "RegistController.h"
#import "NSMMotionManager.h"

@interface LoginModeButton : NSMButton
@end

@implementation LoginModeButton
- (void)setHighlighted:(BOOL)highlighted {
    [UIView animateWithDuration:0.1 animations:^{
        self.alpha = highlighted? 0.5: 1;
    }];
}
@end

@interface LoginMotionView : UIView
@property (nonatomic) CGFloat offset;
@property (nonatomic, strong) UIImage *image;
@property (nonatomic, strong) UIImageView *imageView;
@end

@implementation LoginMotionView
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _offset = 64.0f;
        _imageView = UIImageView.new;
        [self addSubview:_imageView];
    }
    return self;
}

- (void)setImage:(UIImage *)image {
    _image = image;
    
    _imageView.image = image;
    _imageView.size = CGSizeMake(self.width+_offset*2, self.height+_offset*2);
    _imageView.center = CGSizeCenter(self.size);
}

- (void)startUpdates {
    @nsm_weak(self)
    [_motionManager startDeviceMotionUpdates:^(double x, double y, double z) {
        @nsm_strong(self)
        [UIView animateKeyframesWithDuration:0.3 delay:0 options:UIViewKeyframeAnimationOptionCalculationModeDiscrete animations:^{
            float offsetX = x * self.offset * 0.2;
            CGFloat offsetY = y * self.offset * 0.2;
            offsetX = MIN(MAX(-self.offset, offsetX), self.offset);
            offsetY = MIN(MAX(-self.offset, offsetY), self.offset);
            self.imageView.center = CGPointMake(self.width/2 + offsetX,
                                                self.height/2 + offsetY);
        } completion:nil];
    }];
}

- (void)stopUpdates {
    [_motionManager stopAllUpdates];
}
@end

@interface LoginController ()
@property (nonatomic, strong) UITextField *accountField;
@property (nonatomic, strong) UITextField *pwdField;
@property (nonatomic, strong) NSMButton *submitBtn;
@property (nonatomic, strong) MyLinearLayout *contentLayout;
@property (nonatomic, strong) LoginMotionView *liveImageView;
@end

@implementation LoginController

- (UIStatusBarStyle)preferredStatusBarStyleWhenBasedOnAppDelegate {
    return UIStatusBarStyleLightContent;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    [_liveImageView startUpdates];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    [_liveImageView stopUpdates];
}

- (void)didInitialize {
    [super didInitialize];
    
     self.navBarHiddenWhenAppear = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.contentLayout setNeedsLayout];
    [self.contentLayout layoutIfNeeded];
    
    // 方式1 局中对齐
    CGFloat marginTop = MAX((kScreenHeight-self.contentLayout.height)/2, kNavBarHeight);
    // 方式2 顶部对齐
    marginTop = kNavBarHeight+44;
    self.contentLayout.padding = UIEdgeInsetsMake(marginTop, 44, 0, 44);
}

- (void)initSubviews {
    [super initSubviews];
    
    // [self initNavigationItems];
    
    _liveImageView = [[LoginMotionView alloc] initWithFrame:kScreenBounds];
    _liveImageView.size = kScreenSize;
    _liveImageView.image = NameImage(@"global_login_bg");
    [self.view addSubview:_liveImageView];
    
    [self initContentView];
}

- (void)initNavigationItems {
    UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemStop target:self action:@selector(onClickCancel:)];
    self.navigationItem.leftBarButtonItem = cancelItem;
}

- (void)initContentView {
    MyLinearLayout *layout = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Vert];
    layout.width = kScreenWidth;
    layout.padding = UIEdgeInsetsMake(0, 44, 0, 44);
    layout.gravity = MyGravity_Horz_Center;
    [self.view addSubview:layout];
    _contentLayout = layout;
    
    {
        // 标题
        UILabel *label = UILabel.new;
        label.myHorzMargin = 0;
        label.wrapContentHeight = YES;
        label.myBottom = 44;
        [layout addSubview:label];
        
        NSMutableAttributedString *attr = NSMutableAttributedString.new;
        [attr appendAttributedString:AttributedString(@"登录",
                                                      BoldSystemFont(36),
                                                      COLOR_4,
                                                      @"",
                                                      SystemFont(16),
                                                      COLOR_4,
                                                      NSTextAlignmentLeft,
                                                      6)];
        [attr appendAttributedString:AttributedString(@"\n欢迎来到 ",
                                                      SystemFont(16),
                                                      WhiteColor(0.8, 1),
                                                      kAppBundleName,
                                                      BoldSystemFont(16),
                                                      COLOR_4,
                                                      NSTextAlignmentLeft,
                                                      6)];
        label.attributedText = attr;
    }
    
    NSArray <NSDictionary*> *data = @[@{@"placeholder": @"手机号",
                                        @"keyboardType": @(UIKeyboardTypePhonePad),
                                        @"icon": @"regist_00",
                                        @"id": @"mobile"},
                                      @{@"placeholder": @"密码",
                                        @"keyboardType": @(UIKeyboardTypeAlphabet),
                                        @"icon": @"regist_03",
                                        @"id": @"password"}];
    @nsm_weak(self)
    for (int i=0; i<data.count; i++) {
        UIKeyboardType keyboardType = [data[i][@"keyboardType"] integerValue];
        NSString *key = data[i][@"id"];
        
        UITextField *field = [UITextField new];
        field.myHorzMargin = 0;
        field.height = 48;
        field.tag = i;
        field.font = SystemFont(18);
        field.placeholder = data[i][@"placeholder"];
        field.textColor = COLOR_4;
        field.tintColor = THEME_COLOR;
        field.keyboardType = keyboardType;
        field.secureTextEntry = i?YES:NO;
        field.clearButtonMode = UITextFieldViewModeWhileEditing;
        [field setValue:CustomFont(14) forKeyPath:@"_placeholderLabel.font"];
        [field setValue:WhiteColor(0.8, 1) forKeyPath:@"_placeholderLabel.textColor"];
        [layout addSubview:field];
        
        [field addBlockForControlEvents:UIControlEventEditingChanged block:^(UITextField *sender) {
            @nsm_strong(self)
            if (sender.text.length)
                SetBit(self.maskCode, i);
            else
                ClearBit(self.maskCode, i);
            self.mutableDic[key] = SafeString(sender.text);
            [self checkEnable];
        }];
        
        if (i == 0)
            _accountField = field;
        else {
            field.myTop = 12;
            _pwdField = field;
        }
        
        UIView *leftView = [UIView new];
        leftView.size = CGSizeMake(32, field.height);
        
        UIImageView *icon = [UIImageView new];
        icon.tintColor = WhiteColor(1, 0.8);
        icon.size = CGSizeMake(20, 20);
        icon.centerY = leftView.height/2;
        icon.image = TemplateImage(data[i][@"icon"]);
        [leftView addSubview:icon];
        
        field.leftView = leftView;
        field.leftViewMode = UITextFieldViewModeAlways;
        
        UIView *line = [UIView new];
        line.myHorzMargin = 0;
        line.myHeight = kSinglePixel;
        line.backgroundColor = SEPARATOR_COLOR;
        [layout addSubview:line];
    }
    
    MyLinearLayout *bottomLayout = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Horz];
    bottomLayout.myHorzMargin = 0;
    bottomLayout.myHeight = 48;
    bottomLayout.gravity = MyGravity_Horz_Between;
    [layout addSubview:bottomLayout];
    bottomLayout.gravity = MyGravity_Horz_Between;
    
    NSMButton *forgetBtn = NSMButton.new;
    forgetBtn.mySize = CGSizeMake(100, 48);
    forgetBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    forgetBtn.titleLabel.font = CustomFont(14);
    [forgetBtn setTitleColor:WhiteColor(1, 0.8) forState:UIControlStateNormal];
    [forgetBtn setTitle:@"忘记密码" forState:UIControlStateNormal];
    [forgetBtn addTarget:self action:@selector(onClickForgot:) forControlEvents:UIControlEventTouchUpInside];
    [bottomLayout addSubview:forgetBtn];
    
    NSMButton *registBtn = NSMButton.new;
    registBtn.mySize = CGSizeMake(100, 48);
    registBtn.titleLabel.font = CustomFont(14);
    registBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [registBtn setTitleColor:WhiteColor(1, 0.8) forState:UIControlStateNormal];
    [registBtn setTitle:@"立即注册" forState:UIControlStateNormal];
    [registBtn addTarget:self action:@selector(onClickRegist:) forControlEvents:UIControlEventTouchUpInside];
    [bottomLayout addSubview:registBtn];
    registBtn.myVisibility = MyVisibility_Invisible;
    
    NSMButton *submitBtn = NSMButton.new;
    submitBtn.backgroundColor = THEME_COLOR;
    submitBtn.myTop = 64;
    submitBtn.myHorzMargin = 0;
    submitBtn.height = 44;
    submitBtn.enabled = NO;
    submitBtn.titleLabel.font = BoldSystemFont(17);
    [submitBtn setTitleColor:COLOR_4 forState:UIControlStateNormal];
    [submitBtn addTarget:self action:@selector(onClickSubmit:) forControlEvents:UIControlEventTouchUpInside];
    submitBtn.title = @"登   录";
    [layout addSubview:submitBtn];
    ViewCorner(submitBtn, submitBtn.height/2);
    _submitBtn = submitBtn;
}

- (void)initBarView {
    UIView *barView = UIView.new;
    barView.top = kStatusBarHeight;
    barView.size = CGSizeMake(kScreenWidth, 44);
    [self.view addSubview:barView];
    
    // 取消
    CGFloat iconW = 18;
    NSMButton *cancel = NSMButton.new;
    cancel.size = CGSizeMake(15*2+iconW, barView.height);
    cancel.imageSize = CGSizeMake(iconW, iconW);
    [cancel setImage:NameImage(@"login_cancel_noborder") forState:UIControlStateNormal];
    [cancel addTarget:self action:@selector(onClickCancel:) forControlEvents:UIControlEventTouchUpInside];
    [barView addSubview:cancel];
}

#pragma mark - network

#pragma mark - UITextField
- (BOOL)checkEnable {
    // 0011 = 0x03;
    BOOL enable = ((self.maskCode & 0x03) == 0x03);
    _submitBtn.enabled = enable;
    
    return enable;
}

#pragma mark - action
- (void)onClickCancel:(id)sender {
    [self.view endEditing:YES];
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)onClickForgot:(id)sender {
    [self.view endEditing:YES];
    
    RegistController *vc = [RegistController new];
    vc.title = @"忘记密码";
    vc.apiType = ApiTypeForgot;
    vc.components = @[@(ComponentMobile),
                      @(ComponentSMSCode),
                      @(ComponentPassword)];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)onClickRegist:(id)sender {
    
}

- (void)onClickSubmit:(id)sender {
    EndEditing();
    
    @nsm_weak(self)
    [_networker POST:@"publics/login" parameters:self.mutableDic success:^(NSMResponseObject *responseObject) {
        @nsm_strong(self)
        [self saveLoginData:responseObject.data];
    } empty:nil failure:nil];
}

- (void)saveLoginData:(id)data {
    NSAssert([data isKindOfClass:[NSDictionary class]], @"登录API数据类型错误");
    
    // 将密码保存起来
    NSMutableDictionary *userDic = [(NSDictionary *)data mutableCopy];
    userDic[@"account"] = SafeString(_accountField.text);
    userDic[@"password"] = SafeString(_pwdField.text);
    
    dispatch_async(dispatch_get_main_queue(), ^{
        _keyWindow.isLoading = YES;
    });
    
    @nsm_weak(self)
    [_appCache updateUserInfo:userDic reset:YES complete:^{
//        _appCache.isGuester = NO;
        @nsm_strong(self)
        dispatch_async(dispatch_get_main_queue(), ^{
            _keyWindow.isLoading = NO;
            [_noteCenter postNotificationName:kUserDidLoginNotification object:nil userInfo:nil];
            if (self.presentingViewController) {
                [self dismissViewControllerAnimated:YES completion:^{
                    !self.didLoginSuccess?:self.didLoginSuccess(userDic);
                }];
            } else
                !self.didLoginSuccess?:self.didLoginSuccess(userDic);
        });
    }];
}

@end


@implementation UIViewController (LoginController)
- (void)presentLoginController:(void (^)(LoginController *))hander
                      animated:(BOOL)animated
                    completion:(void (^)(void))completion {
    LoginController *vc = [LoginController new];
    !hander?:hander(vc);
    NSMNavigationController *nav = [NSMNavigationController controller:vc];
    [self presentViewController:nav animated:animated completion:completion];
}
@end


